//
//  HMHomeHeadView.m
//  G05爱鲜蜂
//
//  Created by 源 何 on 16/10/17.
//  Copyright © 2016年 何源. All rights reserved.
//

#import "HMHomeHeadView.h"
#import "HMHomeModel.h"
#import "HMIconsButton.h"
static NSString *identifier = @"HMHomeHeadViewID";

@interface HMHomeHeadView ()< UICollectionViewDelegate,UICollectionViewDataSource >

@property (nonatomic, strong) UICollectionView *circleView;

@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;

@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, strong) UIPageControl *pagecontrol;

@property (nonatomic, strong) NSMutableArray *buttonArray;

@end

@implementation HMHomeHeadView

- (NSMutableArray *)buttonArray{
    if (nil == _buttonArray) {
        _buttonArray = [NSMutableArray array];
    }
    return _buttonArray;
}

- (void)setFocusArray:(NSArray<HMHomeModel *> *)focusArray{
    _focusArray = focusArray;
}
- (void)setIconArray:(NSArray<HMHomeModel *> *)iconArray{
    _iconArray = iconArray;
    int index = 0;
    //遍历按钮
    for (HMIconsButton *btn in self.buttonArray) {
        HMHomeModel *model = _iconArray[index];
        NSString *imageStr = model.img;
        NSURL *url = [NSURL URLWithString:imageStr];
        [btn sd_setImageWithURL:url forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"v2_placeholder_square"]];
        if (!model.name) {
            [btn setTitle:@"占位文字" forState:UIControlStateNormal];
        } else {
            [btn setTitle:model.name forState:UIControlStateNormal];
        }
        btn.titleLabel.textAlignment = NSTextAlignmentCenter;
        btn.titleLabel.font = [UIFont systemFontOfSize:12];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        index++;
    }
}


- (UICollectionViewFlowLayout *)flowLayout{
    if (nil == _flowLayout) {
        _flowLayout = [[UICollectionViewFlowLayout alloc] init];
    }
    return _flowLayout;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupUI];
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:1];
        [self.circleView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
    return self;
}

//加载UI界面
- (void)setupUI{
    
    //轮播
    [HMHomeModel downloadWithKey:@"focus" andSuccessBlock:^(NSArray *array) {
        self.focusArray = array;
        [self.circleView reloadData];
    } andFailureBlock:^{
        NSLog(@"轮播获取失败");
    }];
    
    //按钮
    [HMHomeModel downloadWithKey:@"icons" andSuccessBlock:^(NSArray *array) {
        self.iconArray = array;

    } andFailureBlock:^{
        NSLog(@"轮播获取失败");
    }];
    
    self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.flowLayout.itemSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, ([UIScreen mainScreen].bounds.size.height/3) * 0.75);
    self.flowLayout.minimumLineSpacing = 0;
    self.flowLayout.minimumInteritemSpacing = 0;
    
    UICollectionView *circleView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.flowLayout];
    self.circleView = circleView;
    [self.circleView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:identifier];
    
    self.circleView.delegate = self;
    self.circleView.dataSource = self;
    
    self.circleView.bounces = NO;
    self.circleView.showsHorizontalScrollIndicator = NO;
    self.circleView.pagingEnabled = YES;
    
    [self addSubview:circleView];  //默认执行刷新
    
    [circleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.top.trailing.equalTo(self);
        make.height.equalTo(self).multipliedBy(0.75);
    }];

    CGFloat btnW = [UIScreen mainScreen].bounds.size.width / 4;
    CGFloat btnH = ([UIScreen mainScreen].bounds.size.height / 3) * 0.25;
    
    for (int i = 0; i < 4; i++) {
        
#warning 设置按钮
        HMIconsButton *btn = [[HMIconsButton alloc] initWithFrame:CGRectMake(i * btnW, self.bounds.size.height * 0.75, btnW, btnH)];
        
        HMHomeModel *model = _iconArray[i];
        
        NSString *imageStr = model.img;
        NSURL *url = [NSURL URLWithString:imageStr];
        [btn sd_setImageWithURL:url forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"v2_placeholder_square"]];
        if (!model.name) {
            [btn setTitle:@"占位文字" forState:UIControlStateNormal];
        } else {
            [btn setTitle:model.name forState:UIControlStateNormal];
        }
        btn.titleLabel.textAlignment = NSTextAlignmentCenter;
        btn.titleLabel.font = [UIFont systemFontOfSize:12];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [self.buttonArray addObject:btn];
        [self addSubview:btn];
    }
    UIPageControl *pageControl = [[UIPageControl alloc] init];
    pageControl.pageIndicatorTintColor = [UIColor colorWithWhite:0.502 alpha:1.0];
    pageControl.currentPageIndicatorTintColor = [UIColor colorWithWhite:1.0 alpha:1.0];
    pageControl.numberOfPages = 5;
    self.pagecontrol = pageControl;
    [self addSubview:pageControl];
    
    [pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(self).offset(-8);
        make.bottom.equalTo(self.mas_bottom).offset(-([UIScreen mainScreen].bounds.size.height/3) * 0.25 + 5);
    }];
    
    NSTimer *timer = [NSTimer timerWithTimeInterval:2 target:self selector:@selector(playPicture) userInfo:nil repeats:YES];
    
    //添加到运行循环里
    self.timer = timer;
    
    [[NSRunLoop currentRunLoop]addTimer:timer forMode:NSRunLoopCommonModes];
}

-(void)playPicture{
    
    //1.拿到当前的偏移量
    CGFloat offsetX = self.circleView.contentOffset.x;
    
    //2.修改偏移量
    offsetX += self.circleView.bounds.size.width;
    
    //3.赋值
    [self.circleView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
}

#pragma mark
#pragma mark -- UICollectionViewDelegate,UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 3;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.focusArray.count ? self.focusArray.count : 5;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    
    HMHomeModel *model = self.focusArray[indexPath.item];
    NSString *imageStr = model.img;
    NSURL *url = [NSURL URLWithString:imageStr];
    UIImageView *circleView = [[UIImageView alloc] init];

    [circleView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"v2_placeholder_full_size"]];
    
    [cell.contentView addSubview:circleView];
    
    [circleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(cell.contentView);
    }];
    
    return cell;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    int pageIndex =  scrollView.contentOffset.x / self.circleView.frame.size.width;
    
    //模运算
    pageIndex = pageIndex % 5;
    
    self.pagecontrol.currentPage = pageIndex;
}

#pragma mark
#pragma mark -- 滚动结束之后,调回到中间section对应的item位置
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    //contentoffset / 屏幕的宽度
    int pageIndex =  scrollView.contentOffset.x / self.circleView.frame.size.width;
    
    //模运算
    pageIndex = pageIndex % 5;
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:pageIndex inSection:1];
    [self.circleView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
}

-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    NSInteger pageIndex =  scrollView.contentOffset.x / self.circleView.frame.size.width;
    
    //模运算
    pageIndex = pageIndex % 5;
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:pageIndex inSection:1];
    [self.circleView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
}

//将要开始拖拽
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    self.timer.fireDate = [NSDate distantFuture];
}
//停止拖拽

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    self.timer.fireDate = [NSDate dateWithTimeIntervalSinceNow:2];
}



@end
